<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card v-loading="loading">
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-col>
                <el-button icon="el-icon-plus" size="small" type="primary" @click="showDialog = true">新增角色</el-button>
              </el-col>
            </el-row>
            <!-- 表格 -->
            <el-table border="" :data="list">
              <el-table-column type="index" :index="indexFn" label="序号" width="120" />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="assignPerm(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="deleteRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-col align="center">
                <el-pagination
                  :current-page="query.page"
                  :page-sizes="[2, 4, 6, 8]"
                  :page-size="query.pagesize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                  hide-on-single-page
                  @size-change="changeSize"
                  @current-change="changeCurrent"
                />
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改" type="info" show-icon :closable="false" />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyInfo.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyInfo.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input disabled style="width:400px" :value="companyInfo.mailbox" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" :rows="3" disabled style="width:400px" :value="companyInfo.remarks" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog title="编辑弹层" :visible="showDialog" @close="closeDialog">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="closeDialog">取消</el-button>
            <el-button size="small" type="primary" @click="btnOk">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <el-dialog title="分配权限" :visible.sync="showPermDialog">
        <!-- check-on-click-node true 点击文字可以选中节点 -->
        <!-- expand-on-click-node false 点击文字不可以收起节点 -->

        <el-tree
          ref="tree"
          :data="permData"
          :props="{label:'name'}"
          show-checkbox
          default-expand-all
          node-key="id"
          :default-checked-keys="selectCheck"
          :check-strictly="true"
          :check-on-click-node="true"
          :expand-on-click-node="false"
        />
        <!-- 确定 取消 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="small" @click="btnPermOK">确定</el-button>
            <el-button size="small" @click="btnPermCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getRoleList, getCompanyInfo, deleteRole, getRoleDetail, updateRole, addRole, assignPerm } from '@/api/setting'
import { getPermissionList } from '@/api/permissions'
import { transArray2Tree } from '@/utils'

export default {
  name: 'Settings',
  data() {
    return {
      query: {
        page: 1,
        pagesize: 2
      },
      total: 0,
      list: [],
      loading: false,
      companyInfo: {},
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },
      showPermDialog: false,
      roleId: null,
      permData: [],
      selectCheck: []
    }
  },
  computed: {
    ...mapGetters(['companyId'])
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    async getCompanyInfo() {
      this.companyInfo = await getCompanyInfo(this.companyId)
    },
    async getRoleList() {
      this.loading = true
      const { total, rows } = await getRoleList(this.query)
      this.total = total
      this.list = rows
      this.loading = false
    },
    changeSize(pagesize) {
      this.query.page = 1
      this.query.pagesize = pagesize
      this.getRoleList()
    },
    changeCurrent(page) {
      this.query.page = page
      this.getRoleList()
    },
    indexFn(index) {
      return (this.query.page - 1) * this.query.pagesize + (index + 1)
    },
    async deleteRole(id) {
      try {
        await this.$confirm('确认删除吗? ')
        await deleteRole(id)
        // this.query.page = 1
        if (this.list.length === 1 && this.query.page > 1) {
          this.query.page--
        }
        await this.getRoleList()
        this.$message.success('删除成功!')
      } catch (e) {
        // console.log(e)
      }
    },
    async editRole(id) {
      this.roleForm = await getRoleDetail(id)
      this.showDialog = true
    },
    btnOk() {
      this.$refs.roleForm.validate(async valid => {
        if (valid) {
          let info = '更新成功!'
          if (this.roleForm.id) {
            await updateRole(this.roleForm)
          } else {
            await addRole(this.roleForm)
            info = '新增成功!'
          }
          await this.getRoleList()
          this.$message.success(info)
          this.showDialog = false
        }
      })
    },
    closeDialog() {
      this.roleForm = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    async assignPerm(id) {
      this.roleId = id

      this.permData = transArray2Tree((await getPermissionList()).filter(item => item.enVisible === '1'), '0')

      const { permIds } = await getRoleDetail(id)
      this.selectCheck = permIds
      this.showPermDialog = true
    },
    async btnPermOK() {
      // console.log(this.selectCheck)
      // console.log(this.$refs.tree.getCheckedKeys())
      await assignPerm({
        id: this.roleId,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      this.$message.success('分配权限成功! ')
      this.showPermDialog = false
    },
    btnPermCancel() {
      this.permData = []
      this.selectCheck = []
      this.showPermDialog = false
    }
  }
}
</script>
